include('shared.lua')

language.Add("naquadah_bomb", "Naquadah Bomb")

local cycleInterval = 0.5
local showCodeWindow = false

function OnUserMessage(userMessage)
   showCodeWindow = userMessage:ReadBool()
end

usermessage.Hook("naquadah_bomb", OnUserMessage)

function ENT:Think()
   self:NextThink(CurTime() + cycleInterval)
   
   if(showCodeWindow == true) then
      showCodeWindow = false
      self:ShowCodeWindow()
   end
   
   return true
end

function ENT:ShowCodeWindow()
   local codeWindow = self:CreateCodeWindow()
   
   codeWindow:MakePopup()
end

function ENT:CreateCodeWindow()
   local ALIGN_RIGHT = 6
   local padding = 20
   
   local function GetRight(panel)
      return panel:GetPos() + panel:GetWide()
   end
   
   local CodeWindow = vgui.Create("DFrame")
   CodeWindow:SetDeleteOnClose(true)
   CodeWindow:SetTitle("Enter Detonation Code")
   
   CodeWindow.CodeBoxLabel = Label("Detonation Code: ", CodeWindow)
   CodeWindow.CodeBoxLabel:SetPos(padding, padding + 50)
   CodeWindow.CodeBoxLabel:SetContentAlignment(ALIGN_RIGHT)
   CodeWindow.CodeBoxLabel:SizeToContents()
   
   CodeWindow.CodeBox = vgui.Create("DTextEntry", CodeWindow)
   CodeWindow.CodeBox:SetPos(GetRight(CodeWindow.CodeBoxLabel) + padding, padding + 50)
   CodeWindow.CodeBox:SetWidth(100)
   CodeWindow.CodeBox:SetEditable(true)
   CodeWindow.CodeBox:SetEnterAllowed(true)
   CodeWindow.CodeBox.OnEnter = function()
      local playerDistance = self:GetPos():Distance(LocalPlayer():GetPos())
      
      if(playerDistance < 100) then
         if(self:GetNWInt("State", 1) ~= 3) then
            RunConsoleCommand("StartDetonation", self:EntIndex(), tostring(CodeWindow.CodeBox:GetValue())) 
         else
            RunConsoleCommand("AbortDetonation", self:EntIndex(), tostring(CodeWindow.CodeBox:GetValue())) 
         end
      else
         LocalPlayer():PrintMessage(HUD_PRINTCENTER, "You are too far away to enter the code.")
      end
      
      CodeWindow:Close()
   end
   
   local frameWidth = GetRight(CodeWindow.CodeBox) + padding
   local frameHeight = (padding * 2) + CodeWindow.CodeBox:GetTall() + 100
   
   CodeWindow:SetSize(frameWidth, frameHeight)
   CodeWindow:AlignBottom(200)
   CodeWindow:CenterHorizontal()
   
   CodeWindow.CodeBox:RequestFocus()
   
   return CodeWindow
end
